<template>
  <div class="crud-table">
    <div class="crud-toolbar">
      <el-button type="primary" @click="$emit('add')">新增</el-button>
      <el-button type="warning" :disabled="!selectedRow" @click="$emit('edit', selectedRow)">编辑</el-button>
      <el-button type="danger" :disabled="!selectedRow" @click="$emit('delete', selectedRow)">删除</el-button>
      <slot name="toolbar-extra"></slot>
    </div>
    <el-table
      :data="data"
      style="width: 100%"
      @row-click="handleRowClick"
      :row-class-name="rowClassName"
      highlight-current-row
    >
      <el-table-column
        v-for="col in columns"
        :key="col.prop"
        v-bind="col"
      />
      <slot name="table-extra"></slot>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @update:current-page="$emit('update:page', $event)"
      @update:page-size="$emit('update:pageSize', $event)"
      @size-change="$emit('size-change', $event)"
      @current-change="$emit('page-change', $event)"
      style="margin-top: 16px; text-align: right;"
    />
  </div>
</template>

<script>
import { ref, watch } from 'vue'
export default {
  name: 'CrudTable',
  props: {
    columns: { type: Array, required: true },
    data: { type: Array, required: true },
    total: { type: Number, default: 0 },
    page: { type: Number, default: 1 },
    pageSize: { type: Number, default: 10 }
  },
  emits: ['add', 'edit', 'delete', 'size-change', 'page-change', 'update:page', 'update:pageSize'],
  setup(props, { emit }) {
    const selectedRow = ref(null)
    function handleRowClick(row) {
      selectedRow.value = row
    }
    function rowClassName({ row }) {
      return selectedRow.value === row ? 'selected-row' : ''
    }
    watch(() => props.data, () => {
      selectedRow.value = null
    })
    return {
      selectedRow,
      handleRowClick,
      rowClassName
    }
  }
}
</script>

<style scoped>
.crud-table {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px #aeeeee44;
}
.crud-toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}
.selected-row {
  background: #e0f7fa !important;
}
</style> 